package com.jintoufs.service.bank.impl;

import com.alibaba.fastjson.JSON;
import com.jintoufs.dao.bank.BankCardMapper;
import com.jintoufs.domain.bank.BankCard;
import com.jintoufs.domain.bank.BankInfo;
import com.jintoufs.domain.constants.WxConstant;
import com.jintoufs.domain.sys.Dictionary;
import com.jintoufs.service.bank.BankService;
import com.jintoufs.service.sys.DictionaryService;
import com.jintoufs.util.valid.ValidUtil;
import com.jintoufs.util.weixin.HttpUtil;
import org.cosmos.modules.web.msg.AjaxMsg;
import org.springframework.stereotype.Service;
import sun.security.krb5.internal.PAData;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BankServiceImpl implements BankService {
    @Resource
    private BankCardMapper bankCardMapper;
    @Resource
    private DictionaryService dictionaryService;

    @Override
    public void save(BankCard bankCard, String id) {
        if (!ValidUtil.isEmpty(id)){
            bankCard.setId(id);
            bankCardMapper.insertSelective(bankCard);
        }else {
            bankCardMapper.updateByPrimaryKeySelective(bankCard);
        }
    }

    @Override
    public void delete(String id) {
        bankCardMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<BankCard> selectByParam(Map<String, Object> param) {
        return bankCardMapper.selectByParam(param);
    }

    @Override
    public AjaxMsg getBankInfo(String cardNo) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        Map<String,String> params = new HashMap<>();
        params.put("_input_charset","utf-8");
        params.put("cardNo",cardNo);
        params.put("cardBinCheck","true");
        HttpUtil httpUtil = new HttpUtil();
        try {
            String json = httpUtil.doGet(WxConstant.ALIPAY_BANK_URL,null,params).getBody();
            if (ValidUtil.isEmpty(json)){
                ajaxMsg.setCode(AjaxMsg.FAILURE);
                ajaxMsg.setMessage("获取银行卡信息错误。");
            }else{
                Dictionary dictionary;
                BankInfo bankInfo = JSON.parseObject(json, BankInfo.class);
                params.clear();
                params.put("keyNo",bankInfo.getBank());
                params.put("caption","bankInfo");
                dictionary = dictionaryService.getByParams(params);
                bankInfo.setBankName(dictionary.getKeyValue());
                params.clear();
                params.put("d","cashier");
                params.put("t",bankInfo.getBank());
                bankInfo.setLogoUrl(httpUtil.getUrl(WxConstant.ALIPAY_BANK_LOGO_URL,params));
                bankInfo.setCardNo(cardNo);
                ajaxMsg.setDatas(bankInfo);
            }
        }catch (Exception e){
            e.printStackTrace();
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage("获取银行卡信息错误。");
        }
        return ajaxMsg;
    }
}
